/* eslint-disable @typescript-eslint/no-explicit-any */
/**
 * @name 修改主题色
 */

import { useEffect, useState } from "react";
import classNames from "classnames";

export enum THEME_MODE {
  light = "亮光模式",
  dark = "暗黑模式",
}

const SwitchTheme = () => {
  const [InnerMoon, setInnerMoon] = useState<any>(null);
  const [mode, setMode] = useState<keyof typeof THEME_MODE>("light");

  useEffect(() => {
    // 仅在客户端加载组件
    if (typeof window !== "undefined") {
      import("@theme-toggles/react").then((module) => {
        setInnerMoon(() => module.InnerMoon);
      });
      import("@theme-toggles/react/css/InnerMoon.css");
    }
  }, []);

  useEffect(() => {
    window.addEventListener("storage", listenStorage);

    return () => {
      window.removeEventListener("storage", listenStorage);
    };
  }, []);

  useEffect(() => {
    window.localStorage.setItem("theme", mode);
  }, [mode]);

  // 监听storage的变化
  const listenStorage = (e: StorageEvent) => {
    console.log(e);
  };

  return (
    <div
      className={classNames([
        // 布局样式
        "flex space-x-2 items-center mr-4",
      ])}
    >
      {InnerMoon && (
        <InnerMoon
          className="scale-150"
          // checked={mode === "dark"}
          duration={750}
          placeholder={undefined}
          onPointerEnterCapture={undefined}
          onPointerLeaveCapture={undefined}
          toggled={mode === "dark"}
          toggle={() => {
            const newMode = mode === "light" ? "dark" : "light";
            setMode(newMode);
            document.documentElement.classList.toggle(
              "dark",
              newMode === "dark"
            );
          }}
        />
      )}
    </div>
  );
};

export default SwitchTheme;
